package org.yan.stock.server.client;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

/**
 * @func Regist the client and the stocks of it
 * @author yan
 */
public class ClientRegistry {

	private static final ClientRegistry registry = new ClientRegistry();

	private Map<String, Client> registerMap;

	/**
	 * The max limit of the registers
	 */
	private int threshold;

	private ClientRegistry() {}

	public static ClientRegistry getRegistry() {
		return registry;
	}

	/**
	 * Init the var and the registry
	 */
	public void init(List<Client> clientList, int threshold) {
		this.threshold  = threshold;
		registerMap = new HashMap<String, Client>();
		for(Client client: clientList) {
			registerMap.put(client.getAuthId(), client);
		}
	}

	/**
	 * Add or update the register of map
	 */
	public synchronized void regist(Client client) {
		if (registerMap.size() < threshold || registerMap.get(client.getAuthId()) != null) {
			registerMap.put(client.getAuthId(), client);
		}
	}
	
	/**
	 * Return the register list
	 */
	public synchronized Queue<Client> getRegisters() {
		Set<String> nameSet = registerMap.keySet();
		Queue<Client> clientQueue= new LinkedList<Client>();
		Iterator<String> it = nameSet.iterator();
		while(it.hasNext()) {
			clientQueue.add(registerMap.get(it.next()));
		}
		return clientQueue;
	}

	/**
	 * Delete the register
	 */
	public synchronized void destory(Client client) {
		registerMap.remove(client.getAuthId());
	}

	/**
	 * Clear all registers of map
	 */
	public synchronized  void reset() {
		registerMap.clear();
	}

}
